<?php
namespace Home\Controller;

use Common\Library\BusinessException;
use Common\Library\SendSMS;
use Common\Library\Constant;
use Common\Library\Http\Request;
use Common\Library\Http\Response;
use Think\Controller;
use Think\Exception;
use Think\Log;

class MerchantController extends Controller
{

    public function __construct() {
        parent::__construct();

        try {
            Request::parse();
        } catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
            $this->ajaxReturn($ret);
        }
    }

    public function index(){
        return $this->login();
    }

    /**
     * 商户登录
     */
    public function login()
    {
        try {
            $mobile = I("post.mobile");
            $password = I("post.password");
            if (!is_mobile($mobile) || !$password) {
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }

            $merchantUser = M('MerchantUser')->where(['mobile' => $mobile])->find();
            if (password_unmatched($password, $merchantUser['password'])) {
                BusinessException::throwException(Constant::PASSWORD_NOT_MATCH);
            }

            $data = [
                'id' => $merchantUser['merchant_id'],
                'mobile' => $merchantUser['mobile'],
                'balance' => $merchantUser['balance'],
            ];

            $ret = Constant::getReturn(Constant::SUCCESS);
            $ret['data'] = $data;
        } catch(Exception $e) {
            $ret = ['code'=>$e->getCode(), 'msg'=>$e->getMessage()];
        }

        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    /**
     * 获取商户信息
     * @param string $id
     * @return mixed|void
     */
    public function getInfo() {
        try {
            $id = I("post.id", 0, 'intval');
            $ret = Constant::getReturn(Constant::FAILED);
            $merchantLogin = M("MerchantUser");
            $merchant = $merchantLogin->where(['merchant_id'=> $id])->find();
            if ($merchant) {
                $ret = Constant::getReturn(Constant::SUCCESS);
                unset($merchant['password'], $merchant['salt']);
                $ret['data'] = $merchant;
                return $this->ajaxReturn($ret);
            }
        }
        catch(Exception $e) {
            $ret = ['code'=>$e->getCode(), 'msg'=>$e->getMessage()];
        }
        return $this->ajaxReturn($ret);
    }

    /**
     * 获取在该商户的消费记录
     * @param $id
     */
    public function getSaleList() {
        try {
            $merchantId = I('post.merchant_id', 0, 'int');
            D('Merchant')->has($merchantId);
            Log::write('getSaleList1'.$merchantId,Log::DEBUG);
            $offset = I("post.offset", 0, 'intval');
            $length = I("post.length", 20, 'intval');

            $historyCount = D("ConsumeHistory")->where(['merchant_id'=> $merchantId, 'status'=>1])->count();

            $history = M("ConsumeHistory")->field("m.real_name as customer_name,consume_history.add_time as consume_time,
           (consume_history.amount)+(consume_history.discount_first_order)+(consume_history.down_payment) as consume_amount")->
            join("customer m on m.id=consume_history.customer_id", 'LEFT')->
            where(['consume_history.merchant_id'=> $merchantId, 'consume_history.status'=>['in', '1,4,3']])->
            order(['consume_history.id' => 'desc'])->
            limit($offset, $length)->select();

            $history = $history && is_array($history) ? $history : [];
            Log::write('销售记录'.json_encode($history),Log::DEBUG);
            $commission = M("Merchant")->field('is_commission,is_keyman')->where(['id'=> $merchantId])->find();
           if($commission['is_commission']==1 && $commission['is_keyman']==1){
                $commision_status=1;//是否支持佣金状态 0-无 1-有
            }else{
                $commision_status=0;//是否支持佣金状态 0-无 1-有
            }
            Log::write('是否支持佣金：'.$commision_status,Log::DEBUG);
            $ret = Constant::getReturn(Constant::SUCCESS);
            $ret['total'] = $historyCount;
            $ret['offset'] = $offset;
            $ret['length'] = $length;
            $ret['commision_status']=$commision_status;
            $ret['data'] = $history;
            $ret['balance'] = (int)M('MerchantUser')->where(['merchant_id' => $merchantId])->getField('balance');
        } catch(Exception $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }
        Log::write('zhichi'.json_encode($ret),Log::DEBUG);
        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    /*****************
     * 商户取现
     ******************/
    public function withdraw()
    {
        try {
            $merchantId = I('merchant_id', 0, 'int');
            $money = I("money", 0, 'int');

            $merchantUser = M("MerchantUser")->where(['merchant_id'=> $merchantId])->find();

            if (!$money || !$merchantUser) {
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }

            if ($merchantUser['balance'] < $money) {
                BusinessException::throwException(Constant::OUT_OF_RANGE);
            }

            $data = [
                'merchant_id' => $merchantId,
                'money' => $money,
                'status' => 0,
                'add_time' => time(),
            ];

            if (!($insertId = D('MerchantWithdrawHistory')->add($data))) {
                BusinessException::throwException(Constant::FAILED);
            }

            $update = [
                'balance' => $merchantUser['balance'] - $money,
            ];

            if (!M('MerchantUser')->where(['merchant_id' => $merchantId])->save($update)) {
                Log::write('提现出错,未减少商户余额。提现申请ID:' . $insertId . ' 提现参数:' . var_export($data));
                // @todo 下发短信报警
            }

            $ret = Constant::getReturn(Constant::SUCCESS);
            $ret['data']['balance'] = $update['balance'];
        } catch (Exception $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    /**
     * 获取商户列表
     */
    public function getNearbyList()
    {
        try {
            $categoryId = I("post.category", 0, 'intval');
            $lat = I("post.lat", '', 'string');
            $lng = I("post.lng", '', 'string');
            $offset = I("post.offset", 0, 'intval');
            $length = I("post.length", 30, 'intval');

            // todo 客户端一期没有做分页,服务器默认值返回前20条
            $length = 50;

            if (!$lat || !$lng) {
                // @todo 跟客户端协商一致后,干掉location字段
                $location = I('post.location', '', 'string');
                $location = explode(',', $location);
                $lat = isset($location[0]) ? $location[0] : '';
                $lng = isset($location[1]) ? $location[1] : '';

                if (!$lat || !$lng) {
                    BusinessException::throwException(Constant::INVALID_PARAMETER);
                }
            }
            $ret = Constant::getReturn(Constant::SUCCESS);
            $where = [
                'status' => 1,
            ];
            if ($categoryId) {
                $where['category'] = $categoryId;
            }
             $merchantList   = D('Merchant')->getNearByList($lat, $lng, $where);
            $ret['offset']  = $offset;
             $ret['length']  = $length;
             $ret['total']   = sizeof($merchantList);
            $ret['data']    = $merchantList ? array_slice($merchantList, $offset, $length) : [];
        } catch(Exception $e) {
            $ret = ['code'=>$e->getCode(), 'msg'=>$e->getMessage()];
        }

        Response::format($ret);
        $this->ajaxReturn($ret);
        }


    /*************************************************************************
     * 功能描述：商户快速注册
     * 创建时间：2016-08-04
     * 入参：
     *     "merchant_name":"商户店名",
     *     "mobile":"商家手机号",
     *     "verify_code":"验证码",
     *     "password":"密码（密文）"
     * 出参：
     *     "code": 0,
     *     "msg": "success"
     *************************************************************************/
    public function signUp()
    {
        try{
            //0.参数校验
            $merchant['name'] = I("post.merchant_name", 0, 'string');
            $merchant['mobile'] = I("post.mobile", 0, 'string');
            $verifyCode = I("post.verify_code", 0, 'intval');
            $merchant['password'] = I("post.password", 0, 'string');
            if(!$merchant['name'] || !$merchant['mobile'] || !$verifyCode || !$merchant['password']){
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }
            //1.校验商户是否注册过（店名唯一，手机号唯一）
            /*$res = M('Merchant')->where(['name' => $merchant['name'], 'status' => ['in','0,1']])->find();
            if($res){
                BusinessException::throwException(Constant::MERCHANT_NAME_EXIST);
            }*/

            //手机号规则校验
            if(!is_mobile($merchant['mobile'])){
                BusinessException::throwException(Constant::INVALID_MOBILE);
            }
            $res = M('MerchantUser')->where(['mobile' => $merchant['mobile']])->order('id desc')->find();
            if($res){
                $result = M('Merchant')->where(['id' => $res['merchant_id'], 'status' => ['in','0,1,3']])->find();
                if($result){
                    BusinessException::throwException(Constant::MERCHANT_MOBILE_EXIST);
                }
            }

            //2.验证码正确性校验
            $sentVerifyCode = SendSMS::getVerifyCode($merchant['mobile'], Constant::VERIFY_CODE_MERCHANT_SIGNUP);
            if (!$sentVerifyCode) {
                BusinessException::throwException(Constant::VERIFY_CODE_TIMEOUT);
            }
            if ($verifyCode != $sentVerifyCode) {
                BusinessException::throwException(Constant::VERIFY_CODE_UNMATCHED);
            }

            //3.录入商户客户信息merchant_user，并商户详情表merchant预留一条信息
            /* 商户app端注册商户，是先有商户基本登陆信息之后，再完善资料，
             * 完善资料时，才会真正的录入商户详细信息，与BOSS后台正好相反，因此需
             * 要预录入一条空的商户详细信息。
             */
            $ins = D('MerchantUser')->saveMerchantUser($merchant);
            if($ins){
                $ret = Constant::getReturn(Constant::SUCCESS);
            }else{
                BusinessException::throwException(Constant::FAILED);
            }

        }catch (BusinessException $e){
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }
        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    /*************************************************************************
     * 功能描述：商户登陆
     * 创建时间：2016-08-04
     * 入参：
     *     "mobile": "商户手机号",
     *     "password": "商户登录密码(密文)"
     * 出参：
     *     "code": 0,
     *     "msg": "success"
     *     "data":{
     *          商户信息json格式
     *      }
     *************************************************************************/
    public function signIn()
    {
        try{
            //0.参数校验
            $mobile = I("post.mobile", 0, 'string');
            $password = I("post.password", 0, 'string');
            $push_id = I("post.push_id", 0, 'string');
            if(!$mobile || !$password){
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }
            //1.手机号规则校验
            if(!is_mobile($mobile)){
                BusinessException::throwException(Constant::INVALID_MOBILE);
            }
            //2.商户有效性校验
            $res = M('MerchantUser')->where(['mobile' => $mobile])->order('id desc')->find();
            if(!$res){
                BusinessException::throwException(Constant::MERCHANT_NOT_FOUND);
            }
            //3.密码规则校验(待确认)

            //4.商户密码正确性校验
            if (!$res['password']) {
                BusinessException::throwException(Constant::UNSET_PAY_PASS);
            }
            if (password_unmatched($password, $res['password'])) {
                BusinessException::throwException(Constant::PASSWORD_NOT_MATCH);
            }
            //5.获取商户数据，客户端需要
            $marchant = M('Merchant')->where(['id' => $res['merchant_id'], 'status' => ['neq', '2']])->find();
            if(!$marchant){
                BusinessException::throwException(Constant::MERCHANT_NOT_FOUND);
            }
            if($marchant['push_id']==NULL){
                M()->query("UPDATE merchant SET push_id = '$push_id' WHERE  id = ".$res['merchant_id']);
            }
            $marchant['add_time'] = date('Y-m-d', $marchant['add_time']);
            $marchant['mobile'] = $res['mobile'];
            $marchant['balance'] = $res['balance'];
            $ret = Constant::getReturn(Constant::SUCCESS);
            $ret['data'] = $marchant;
        }catch (BusinessException $e){
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }
        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    /*************************************************************************
     * 功能描述：商户登出
     * 创建时间：2016-08-04
     * 入参：
     *     "merchant_id": "用户ID"
     * 出参：
     *     "code": 0,
     *     "msg": "success"
     *************************************************************************/
    public function logout()
    {
        try {
            //0.获取上行参数
            $merchantId = I('post.merchant_id', 0, 'int');
            if(!$merchantId){
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }
            $ret = Constant::getReturn(Constant::SUCCESS);

        }catch (BusinessException $e){
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }
        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    public function saveInfo()
    {
        try{
            //0.参数判断
            $data['merchant_id'] = I('post.merchant_id', 0, 'int');
            $data['merchant_name'] = I('post.merchant_name', 0, 'string');
            $data['owner_name'] = I('post.owner_name', 0, 'string');
            $data['operate_year'] = I('post.operate_year', 0, 'int');
            $data['sales_per_month'] = I('post.sales_per_month', 0, 'string');
            $data['address'] = I('post.address', 0, 'string');
            $data['addrStr'] = I('post.addrStr', 0, 'string');

            $data['id_num'] = I('post.id_num', 0, 'string');
            $data['coordinate'] = I('post.location', 0, 'string');//坐标
            $arr = explode(",",$data['coordinate']);
            $data['lng'] = $arr[0];
            $data['lat'] = $arr[1];
            $data['county_id'] = 0;

            $country_name = I('post.country', 0, 'string');//县级名字
            $city_name = I('post.city', 0, 'string');//城市
            $country = M('position_county')->where(['county_name'=>$country_name])->field('county_id,city_id')->select();
            if(count($country)>=2){
              foreach($country as $k => $v){
                  $city_is = M('position_city')->where("city_id=".$v['city_id'])->find();
                  if($city_is['city_name']==$city_name){
                    $data['county_id'] = $country[$k]['county_id'];
                  }
              }
                if($data['county_id']==0){
                    $data['county_id'] = $country[0]['county_id'];
                }

            }else{
                $data['county_id'] = $country[0]['county_id'];
            }
            if(!$data['merchant_id'] || !$data['merchant_name'] || !$data['owner_name'] || !$data['operate_year']
                || !$data['sales_per_month'] || !$data['address'] || !$data['id_num']){
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }
            if(strlen($data['id_num']) != 18){
                BusinessException::throwException(Constant::MERCHANT_CREDIT_ERROR);
            }

            //1.校验商户是否存在
            $res = D('Merchant')->has(['id' => $data['merchant_id'], 'status' => ['in', '0,1,3']]);
            if(!$res){
                BusinessException::throwException(Constant::MERCHANT_NOT_FOUND);
            }

            //2.保存商户信息
            $merchantId = $data['merchant_id'];
            unset($data['merchant_id']);
            $ret = M('Merchant')->where(['id' => $merchantId])->save($data);
            if(false !== $ret || 0 !== $ret){
                $ret = Constant::getReturn(Constant::SUCCESS);
            }else{
                BusinessException::throwException(Constant::FAILED);
            }
        }catch (BusinessException $e){
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }
        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    /*******************************************************************************************
     * 功能描述：商户密码重置
     * 创建日期：2016-08-05
     * 入参：
     *     "mobile": "商户ID",
     *     "password": "经加密后的密文(需要客户端与服务端统一规则)",
     *     "verify_code": "验证码"
     * 出参：
     *     "code": 0,
     *     "msg": "success"
     *******************************************************************************************/
    public function resetPassword()
    {
        try{
            //0.获取上行参数
            $mobile = I('post.mobile', 0, 'string');  //用户ID
            $password = I('post.password', '', 'string');  //密码
            $verifyCode = I('post.verify_code', 0, 'int'); //验证码
            if(!$mobile || !$password || !$verifyCode){
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }

            //1.根据客户id校验用户是否存在
            $merchant = M('MerchantUser')->where(['mobile' => $mobile])->order('id desc')->find();
            if(!$merchant){
                BusinessException::throwException(Constant::MERCHANT_NOT_FOUND);
            }

            //2.验证码校验
            $sentVerifyCode = SendSMS::getVerifyCode($mobile, Constant::VERIFY_CODE_MERCHANT_MODPWD);
            if (!$sentVerifyCode) {   //验证码超时
                BusinessException::throwException(Constant::VERIFY_CODE_TIMEOUT);
            }
            if ($verifyCode != $sentVerifyCode) {  //验证码不正确
                BusinessException::throwException(Constant::VERIFY_CODE_UNMATCHED);
            }

            //3.密码重置
            $res = M('MerchantUser')->where(['id' => $merchant['id']])->setField('password', get_enc_password($password));
            if($res){
                $ret = Constant::getReturn(Constant::SUCCESS);
            }else{
                BusinessException::throwException(Constant::FAILED);
            }
        }catch (BusinessException $e){
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }
        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    /**
     * 获取商家提现历史
     */
    public function getWithdrawHistory()
    {

         try {
            $merchantId = I('post.merchant_id', 0, 'int');
            $merchant = M('Merchant')->where(['merchant_id' => $merchantId])->find();
            if(empty($merchant)){
              BusinessException::throwException(Constant::MERCHANT_NOT_FOUND);
            }
            $offset = I("post.offset", 0, 'intval');
            $length = I("post.length", 20, 'intval');
            $get_type = I("post.get_type");//提现类型 0-销售额 1佣金
            $historyCount = M("MerchantPayLog")->where(['merchant_id'=> $merchantId,'pay_type'=>'0'])->count();
            $history = M("MerchantPayLog")->field("id,money as amount,create_time as withdraw_time,trade_state as status")->where(['merchant_pay_log.merchant_id'=> $merchantId,'pay_type'=>'0'])->order(['merchant_pay_log.id' => 'desc'])->limit($offset, $length)->select();
            $history = $history && is_array($history) ? $history : [];
            foreach($history as $k=>$v){
                //$history[$k]['withdraw_time']=substr($history[$k]['withdraw_time'],5);
                if($v['status']==1){
                   $history[$k]['status']="提现成功";
                }else if($v['status']==3){
                   $history[$k]['status']="提现失败";
                }else if($v['status']==0){
                   $history[$k]['status']="转账中";
                }
            }
             if($get_type==1){
                 $historyCount = M("MerchantCommissionLog")->where(['merchant_id'=> $merchantId])->count();
                 $history1 = M("MerchantCommissionLog")->field("id,money as amount,create_time as withdraw_time")->where(['merchant_id'=> $merchantId])->order(['id' => 'desc'])->limit($offset, $length)->select();
                 $history = $history1 && is_array($history1) ? $history1 : [];
             }
            $ret = Constant::getReturn(Constant::SUCCESS);
            $ret['total'] = $historyCount;
            $ret['offset'] = $offset;
            $ret['length'] = $length;
            $ret['data'] = $history;
        } catch(Exception $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }
        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    /*获取可绑定卡的银行列表*/
    public function getBankList() {
        try {
            $merchantId = I('post.merchant_id', 0, 'int');
            D('Merchant')->has($merchantId);

            $MerchantBankInfo = D("MerchantBankInfo")->getPublicBankList();
            $MerchantBankList = array();
            if($MerchantBankInfo) {
                foreach($MerchantBankInfo as $v) {
                    $MerchantBankList[]= array("bank_id"=>$v[2],"bank_name"=>$v[1]);
                
                }
            }
            $ret = Constant::getReturn(Constant::SUCCESS);
            $ret['data'] = $MerchantBankList;
        } catch(Exception $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    /*绑定提现银行卡*/
    public function bindBankCard() {
        try {

            $merchantId    = I('post.merchant_id', 0, 'int');

            $cardUserName   = I('post.card_owner', '', 'string');
            $cardNum        = I('post.bank_card', 0, 'string');
            $reservedMobile = I('post.reserve_mobile', 0, 'mobile');
            //$card_type = I('post.card_type', 0, 'string');
            $card_type  = 0; //目前写死，对私
            $bank_id = I('post.bank_id', '', 'string');
            $bank_brhname = I('post.bank_brhname', '', 'string');
            $verifyCode     = I('post.verify_code', 0, 'int');
            $id_num = I('post.id_num', '', 'string');

            if (!$cardUserName || !$cardNum || !$reservedMobile || !$verifyCode || !$id_num ) {
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }

            $sentVerifyCode = SendSMS::getVerifyCode($reservedMobile, $_type=Constant::VERIFY_CODE_TYPE_BIND);
            if (!$sentVerifyCode) {
                BusinessException::throwException(Constant::VERIFY_CODE_TIMEOUT);
            }

            if (!$verifyCode || $verifyCode !== $sentVerifyCode) {
                BusinessException::throwException(Constant::VERIFY_CODE_UNMATCHED);
            }

            $userinfo = D('Merchant')->has($merchantId);
            $identity_code = $userinfo['id_num'];

            $map = [
                'merchant_id' => $merchantId,
            ];

            $MerchantBankInfo = M('MerchantBankInfo');
            if ($MerchantBankInfo->Where($map)->find()) {
                BusinessException::throwException(Constant::BAND_CARD_EXIST);
            }
            $data = [
                'card_user_name' => $cardUserName,
                'card_type' => $card_type,
                'id_num' => $id_num,
                'bank_id' => $bank_id,
                'card_num' => $cardNum,
                'bank_brhname' => $bank_brhname,
                'reserved_mobile' => $reservedMobile,
                'add_time' => time(),
            ] + $map;

            if (false === ($insertId = $MerchantBankInfo->add($data))) {
                BusinessException::throwException(Constant::BAND_CARD_ADD_FAILED);
            }

            $ret = Constant::getReturn(Constant::SUCCESS);
            //$ret['data'] = $MerchantBankInfo->where(['id' => $insertId])->find();
            SendSMS::rmVerifyCode($reservedMobile, Constant::VERIFY_CODE_TYPE_BIND);
        } catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        Response::format($ret);
        $this->ajaxReturn($ret);
    }


     /********************************************************
     * 功能描述：获取城市信息
     * 创建时间：2016-11-02 16:47
     ********************************************************/
     public function getCity()
     {
        $province_id = I("post.province_id", '', 'int');
        $cityList = [];
        $city = M('position_city')->where(['province_id'=>$province_id])->field('city_id,city_name')->select();
        if(!$city){
                BusinessException::throwException(Constant::MERCHANT_NOT_FOUND);
            }
        foreach ($city as $k=>$v){
                $cityList[$k]['city_id'] = $v['city_id'];
                $cityList[$k]['city_name'] = $v['city_name'];
        }
        $ret = Constant::getReturn(Constant::SUCCESS);
        $ret['data'] = $cityList;
        
        Response::format($ret);
        $this->ajaxReturn($ret);
           
     }

    /********************************************************
     * 功能描述：获取州县信息
     * 创建时间：2016-11-02 17:00
     ********************************************************/
     public function getCounty()
     {
        $city_id = I("post.city_id", '', 'int');
        $data = M('position_county')->where("city_id=$city_id")->getField('id,county_name');
        
        $cityList = [];
        $city = M('position_county')->where(['city_id'=>$city_id])->field('county_id,county_name')->select();
        if(!$city){
                BusinessException::throwException(Constant::MERCHANT_NOT_FOUND);
            }
        foreach ($city as $k=>$v){
                $cityList[$k]['county_id'] = $v['county_id'];
                $cityList[$k]['county_name'] = $v['county_name'];
        }
        $ret = Constant::getReturn(Constant::SUCCESS);
        $ret['data'] = $cityList;
        
        Response::format($ret);
        $this->ajaxReturn($ret);
     }

    /********************************************************
     * 功能描述：更新商户状态为待审核
     * 创建时间：2016-8-19
     ********************************************************/
    public function updToApprove()
    {
        try{
            //0.参数校验
            $merchantId = I('post.merchant_id', 0, 'int');
            $status = I('post.status', 0, 'int');
            if(!$merchantId || Constant::MERCHANT_NEW != $status){
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }

            //1.当前状态校验
            $merchant = M('Merchant')->where(['id'=>$merchantId])->field('status, logo')->find();
            if(!$merchant){
                BusinessException::throwException(Constant::MERCHANT_NOT_FOUND);
            }
            if(Constant::MERCHANT_NEW != $merchant['status']){
                BusinessException::throwException(Constant::MERCHANT_STATUS_ERROR);
            }

            //2.资料完善性校验
            $passLicence = $passIdCard = false;
            $merchant = M('MerchantUploadFile')->where(['merchant_id'=>$merchantId])->select();
            foreach ($merchant as $v){
                if(Constant::CERT_TYPE_LICENCE == $v['type']){
                    $passLicence = true;
                    continue;
                }
                if(Constant::CERT_TYPE_IDCRAD == $v['type']){
                    $passIdCard = true;
                    continue;
                }
            }
            if(!($passLicence && $passIdCard)){
                BusinessException::throwException(Constant::MERCHANT_NOT_OK);
            }

            //3.更新商户状态为待审核
            if(false === M('Merchant')->where(['id'=>$merchantId])->setField('status',Constant::MERCHANT_WAIT_REVIEW)){
                BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
            }
            $ret = Constant::getReturn(Constant::SUCCESS);
        }catch (BusinessException $e){
            $ret = ['code'=>$e->getCode(), 'msg'=>$e->getMessage()];
        }

        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    /******
     * 商户佣金提现 MerchantCommision
     *******/
    public function MerchantCommision()
    {
        $merchantId = I('post.merchant_id', 0, 'int');
        $money = I('post.money', 0, 'int');

        if (!$merchantId || !$money) {
            BusinessException::throwException(Constant::INVALID_PARAMETER);
        }
        $merchant_info = M('MerchantUser')->field('commision_balance,balance')->where(['merchant_id'=>$merchantId])->find();
        if($merchant_info['commision_balance']==0 || $money>$merchant_info['commision_balance']){
            $ret = Constant::getReturn(Constant::OUT_OF_RANGE);//提现金额超出可使用范围
        }else{
            $new_balance = $merchant_info['balance'] + $money;
            $new_commision_balance = $merchant_info['commision_balance'] - $money;
            $info =  M('MerchantUser')->where(['merchant_id'=>$merchantId,'commision_balance'=>$merchant_info['commision_balance']])->setField(['balance'=>$new_balance,'commision_balance'=>$new_commision_balance]);
            if($info==false){
                $ret = Constant::getReturn(Constant::FAILED);//提现失败
            }else{
                //提现日志入库
                $MerchantCommissionLog = M('MerchantCommissionLog');
                $order_id = A('Pay')->trade_no();
                $mer_date = date('Ymd');
                $create_time = date("Y-m-d H:i:s",time());
                //入库
                $data = array(
                    'order_id' => $order_id,
                    'merchant_id' => $merchantId,
                    'money' => $money,
                    'balance_old' => $merchant_info['balance'],
                    'transfer_date'=>$mer_date,
                    'create_time' =>$create_time,
                );
                if (false === ($insertId = $MerchantCommissionLog->add($data))) {
                    BusinessException::throwException('返利提现订单创建失败');
                }
                $ret = Constant::getReturn(Constant::SUCCESS);
                $ret['data']['commision_balance'] = $new_commision_balance;
            }
        }
        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    /*****
     * 商户佣金列表  MerchantCommisionList
     * */
    public function MerchantCommisionList()
    {
        try {
            Log::write("获取佣金列表START".json_encode(I("post.")),Log::DEBUG);
            $merchantId = I('post.merchant_id', 0, 'int');//商户id
            D('Merchant')->has($merchantId);
            $offset = I("post.offset", 0, 'intval');
            $length = I("post.length", 20, 'intval');
            $date = I('post.date_time', '', 'string');
            $date_time = (isset($date) && $date !=0) ? $date:date("Y-m");//时间限制
            $start = strtotime($date_time.'-01');
            $end = strtotime($date_time.'-01 +1 months');
            if(!isset($date)){
               $date='';
            }
            Log::write("POST内容".$start.','.$end.",".$date,Log::DEBUG);
            $type = I('post.type', '', 'string');//类型 0-本月所有佣金明细（type1+type2）; 1-该月非逾期订单佣金明细  2-该月逾期订单佣金明细
            $all_count = D("ConsumeHistory")->where("merchant_id = $merchantId AND status in (1,3) AND type =2 AND add_time >=".$start." AND add_time < ".$end)->count();//本月总条数
            Log::write("总条数：".json_encode($all_count)."SQL:".M()->getLastSQL,Log::DEBUG);
            $commission = D("Merchant")->getCommissionList($merchantId,$offset,$length,$date,$type);

            $ret = Constant::getReturn(Constant::SUCCESS);
            $ret['date_time'] = $date_time;
            $ret['total'] = $all_count;
            $ret['offset'] = $offset;
            $ret['length'] = $length;
            $ret['data'] = $commission;

        }catch (BusinessException $e){
            $ret = ['code'=>$e->getCode(), 'msg'=>$e->getMessage()];
        }

        Response::format($ret);
        $this->ajaxReturn($ret);
    }





}
